package logic

import (
	"context"
	"github.com/pkg/errors"
	"google.golang.org/grpc/status"
	"mall/common/cryptx"
	"mall/common/xerr"
	"mall/service/user/model"

	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/user"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

var ErrUserAlreadyRegisterError = xerr.NewErrMsg("用户不存在")

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	//判断用户是否存在
	userDB, err := l.svcCtx.UserModel.FindOneByUsername(l.ctx, in.Username)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "根据username查询用户信息失败，username:%s,err:%v", in.Username, err)
		}
		return nil, status.Error(500, err.Error())
	}
	//判断密码是否正确
	passwordEncrypt := cryptx.PasswordEncrypt(l.svcCtx.Config.Salt, in.Password)
	logx.Info("passwordEncrypt:", passwordEncrypt)
	if passwordEncrypt != userDB.Password {
		return nil, errors.Wrap(xerr.NewErrMsg("账号或密码不正确"), "密码错误")
	}

	var resp user.LoginResponse
	_ = copier.Copy(&resp, userDB)

	return &resp, nil

	//使用copier.Copy,节省了下面的代码,类似Java的BeanUtils.copyProperties
	/*return &user.LoginResponse{
		Id:     userDB.Id,
		Username:   userDB.Username,
		Gender: userDB.Gender,
		Phone: userDB.Phone,
	}, nil*/
}
